package com.itlong.cloud.controller.sdkV1.cloud.intercom.app;

import com.itlong.cloud.POJO.DTO.sdk.CloudTalkSDKAppFollowDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudTalkSDKAppUserLoginDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkSDKAppDemoLoginVO;
import com.itlong.cloud.POJO.VO.sdk.CloudTalkSDKAppUserVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.CloudTalkErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.project.app.IAppProjectServiceClient;
import com.itlong.cloud.project.app.IAppRoomServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppRegisterServiceClient;
import com.itlong.cloud.user.sdk.ICloudTalkSDKAppUserServiceClient;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/**
 * <desc>
 *      云对讲SDK APP用户控制器
 * </desc>
 *
 * @createDate 2018/05/14
 */
@Controller
@RequestMapping("/cloud/interface")
public class CloudTalkSDKAppUserController {
    //日志记录对象
    private static final Logger LOG = LoggerFactory.getLogger(CloudTalkSDKAppUserController.class);

    @Value("${" + PlatformConstants.CLOUDTALK_SDK_APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;

    @Autowired
    ICloudTalkSDKAppUserServiceClient iCloudTalkSDKAppUserServiceClient;

    @Autowired
    IAppProjectServiceClient iAppProjectServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    IAppRegisterServiceClient iAppRegisterServiceClient;

    @Autowired
    IAppRoomServiceClient iAppRoomServiceClient;
    /**
     * <desc>
     *      SDK 认证
     * </desc>
     *
     * @param dto 登录dto类
     * @param sign 签名
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/11
     */
    @RequestMapping(value = "/app/authentication",method = RequestMethod.POST)
    @ResponseBody
    public MessageVO authentication(CloudTalkSDKAppUserLoginDTO dto,String sign){
        MessageVO messageVO;
        try {
            //验证签名
            if(!Md5EncryptUtil.checkAppSign(dto,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            //验证参数是否匹配
            if(StringUtils.isBlank(dto.getAppId()) || StringUtils.isBlank(dto.getAppsecret()) || StringUtils.isBlank(dto.getPhoneNo()) || StringUtils.isBlank(dto.getLoginDevice())){
                return new MessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            CloudTalkSDKAppUserVO vo = iCloudTalkSDKAppUserServiceClient.authentication(dto);
            if(vo == null){
                messageVO = new MessageVO(CloudTalkErrorCodeEnum.APP_SECRET_ERROR.getErrorCode());
            }else if(StringUtils.isBlank(vo.getPhoneNo())){
                messageVO = new MessageVO(CloudTalkErrorCodeEnum.APP_USER_EXISTS.getErrorCode());
            }else{
                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),vo);
            }
        }catch(Exception e){
            throw new DataAccessException("【CLOUD_TALK_APP_用户板块】SDK认证失败",e);
        }
        return messageVO;
    }



    /**
     * <desc>
     *      注销
     * </desc>
     *
     * @param token
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/14
     */
    @RequestMapping(path = "logout",method = RequestMethod.POST)
    @ResponseBody
    public MessageVO cancel(String token,HttpServletRequest request){
        MessageVO messageVO;
        try{
            iCloudTalkSDKAppUserServiceClient.logout(token);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK_APP_logout】用户注销失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      设置APP是否允许被呼叫
     * </desc>
     *
     * @param dto
     * @param sign
     * @return
     * @author Jiaqi.X
     * @createDate 2018/05/14
     */
    @RequestMapping("/app/setFollowApp")
    public MessageVO setFollowApp(CloudTalkSDKAppFollowDTO dto,String sign){
        MessageVO messageVO;
        try{
            //验证签名
            if(!Md5EncryptUtil.checkAppSign(dto,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isBlank(dto.getAppId()) || StringUtils.isBlank(dto.getPhoneNo())
                    || StringUtils.isBlank(dto.getProjectId()) || StringUtils.isBlank(dto.getFollowApp())){
                return new MessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            CloudTalkSDKAppUserVO vo = iCloudTalkSDKAppUserServiceClient.retrieve(dto.getToken());
            String userId = iCloudTalkSDKAppUserServiceClient.getUserIdByPhoneNum(vo.getPhoneNo());
            iAppProjectServiceClient.setAllowApp(userId, Integer.valueOf(dto.getFollowApp()),dto.getProjectId());
            //推送设备拉取业主信息
            iAppDeviceServiceClient.pushCloudDeviceAuth(dto.getProjectId(),userId,
                    SmartCommunityEnum.PUSH_USER_PROJECT.getCommandType());
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK_APP_setFollowApp】设置APP是否允许被呼叫失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      设置开门密码
     * </desc>
     *
     * @param token 用户token
     * @param projectId 项目id
     * @param doorPwd 开门密码
     * @param sign 签名
     * @return
     * @author Jiaqi.X
     * @createDate 2017/11/13
     */
    @RequestMapping(path = "/setDoorPwd",method = RequestMethod.POST)
    @ResponseBody
    public MessageVO setDoorPwd(String token,String projectId,String doorPwd,String createTime,String sign){
        MessageVO messageVO;
        try {
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("doorPwd",doorPwd);
            params.put("createTime",createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSign(params,sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                ErrorCode errorCode =AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode();
                return  new MessageVO(errorCode);
            }
            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(doorPwd)){
                return new MessageVO(CloudTalkErrorCodeEnum.NOT_PARAM.getErrorCode());
            }else if(!doorPwd.matches("[0-9]{4}")){
                ErrorCode errorCode =AppErrorCodeEnum.OPEN_PASSWORD_IS_ERROR.getErrorCode();
                return new MessageVO(errorCode);
            }
            CloudTalkSDKAppUserVO vo = iCloudTalkSDKAppUserServiceClient.retrieve(token);
            String userId = iCloudTalkSDKAppUserServiceClient.getUserIdByPhoneNum(vo.getPhoneNo());
            //检查用户是否是业主
            if(iAppRegisterServiceClient.countUserAttacheInfoInProject(userId,projectId) < 1){
                ErrorCode errorCode = AppErrorCodeEnum.USER_NOT_OWNER.getErrorCode();
                return new MessageVO(errorCode);
            }
            iAppRoomServiceClient.setOpenPwd(projectId,userId,doorPwd);
            //推送设备拉取业主信息
            iAppDeviceServiceClient.pushCloudDeviceAuth(projectId,userId,
                    SmartCommunityEnum.PUSH_ROOM.getCommandType());
            ErrorCode errorCode =BaseErrorCodeEnum.SUCCESS.getErrorCode();
            messageVO=new MessageVO(errorCode);
        }catch (Exception e){
            throw new DataAccessException("【云对讲SDK_APP_setDoorPwd】设置开门密码失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      demo登录
     * <desc/>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/21
     */
    @ResponseBody
    @PostMapping("cloudTalk/login")
    public MessageVO cloudTalkLogin(String phoneNo, String pswd){
        try {
            if (StringUtils.isBlank(phoneNo) || StringUtils.isBlank(pswd)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!phoneNo.matches("^1[3|4|5|6|7|8|9]\\d{9}$") && !phoneNo.matches("^[A-Za-z\\d]+([-_.][A-Za-z\\d]+)*@([A-Za-z\\d]+[-.])+[A-Za-z\\d]{2,4}$")) {
                return new MessageVO(AppErrorCodeEnum.PHONE_NO_AND_EMAIL_NOT_MATCH.getErrorCode());
            }
            CloudTalkSDKAppDemoLoginVO cloudTalkSDKAppDemoLoginVO = iCloudTalkSDKAppUserServiceClient.cloudTalkLogin(phoneNo, pswd);
            if (cloudTalkSDKAppDemoLoginVO == null) {
                return new MessageVO(AppErrorCodeEnum.USER_NOT_EXIST.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),cloudTalkSDKAppDemoLoginVO);
        } catch (Exception e) {
            throw new DataAccessException("【云对讲SDK_APP_cloudTalkLogin】demo登录失败",e);
        }
    }
}
